package com.shundr.shipper.truck.adapter;

import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.shundr.shipper.R;
import com.shundr.shipper.common.http.CommonRequest;
import com.shundr.shipper.common.util.CommonConfig;
import com.shundr.shipper.common.util.DateUtil;
import com.shundr.shipper.common.util.LImageLoader;
import com.shundr.shipper.common.util.ToastHelper;
import com.shundr.shipper.frame.constant.LContext;
import com.shundr.shipper.frame.http.LHttpRequest;
import com.shundr.shipper.frame.util.StringUtil;
import com.shundr.shipper.truck.ContactTrucker;
import com.shundr.shipper.truck.ContactTrucker.OnCallListener;
import com.shundr.shipper.truck.model.TruckInfo;
import com.shundr.shipper.user.LoginActivity;

/**
 * 
 * CargoAdapter 货源列表适配器
 * 
 * @author larry 2015-4-13 下午4:26:47 
 * @version 1.0.0
 *
 */
public class SearchTruckAdapter extends BaseAdapter{
	private List<TruckInfo> mList;
	private Context mContext;
	private ImageLoader mImageLoader;
	/**
	 * 收藏position
	 */
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case CommonRequest.ADD_FAVORITE_SUCCEED:
				try {
					ToastHelper.toastShort(mContext,msg.obj.toString());
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case LHttpRequest.REQUEST_FAILED:
				try {
					ToastHelper.toastShort(mContext,msg.obj.toString());
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	@Override
	public int getCount() {
		return mList.size();
	}

	@Override
	public Object getItem(int index) {
		return mList.get(index);
	}

	@Override
	public long getItemId(int id) {
		return id;
	}

	public SearchTruckAdapter(List<TruckInfo> mlist, Context mContext) {
		super();
		this.mList = mlist;
		this.mContext = mContext;
		this.mImageLoader = ImageLoader.getInstance();
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup viewGroup) {
		ViewHold viewHold = null;
		if(convertView == null){
			convertView = LayoutInflater.from(mContext).inflate(R.layout.item_search_truck_list,null);
			viewHold = new ViewHold();
			viewHold.ivFull = (ImageView)convertView.findViewById(R.id.iv_car_full);
			viewHold.tvNumber = (TextView) convertView.findViewById(R.id.tv_Number);
			viewHold.tvName = (TextView) convertView.findViewById(R.id.tv_Name);
			viewHold.tvLength = (TextView) convertView.findViewById(R.id.tv_length);
			viewHold.tvWeight = (TextView) convertView.findViewById(R.id.tv_weight);
			viewHold.tvCurrentCity = (TextView) convertView.findViewById(R.id.tv_currentCity);
			viewHold.tvForward = (TextView) convertView.findViewById(R.id.tv_forward);
			viewHold.tvType = (TextView) convertView.findViewById(R.id.tv_type);
			viewHold.layoutCollection = (LinearLayout) convertView.findViewById(R.id.layout_collect);
			viewHold.layoutCall = (LinearLayout) convertView.findViewById(R.id.layout_call);
			viewHold.tvStatus = (TextView) convertView.findViewById(R.id.tv_status);
			viewHold.tvTime = (TextView) convertView.findViewById(R.id.tv_time);
			viewHold.TruckValidation = (ImageView)convertView.findViewById(R.id.iv_validation);
			convertView.setTag(viewHold);
		}else{
			viewHold = (ViewHold) convertView.getTag();
		}
		try {
			final TruckInfo info = mList.get(position);
			
			try {
				mImageLoader.displayImage(info.getTruckPic(), viewHold.ivFull,LImageLoader.mOptions);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			if(StringUtil.isNull(info.getTruckPlateNumber())){
				viewHold.tvNumber.setText("车牌号不详");
				viewHold.tvNumber.setVisibility(View.GONE);
			}else{
				String plateNumber=info.getTruckPlateNumber();
				if(LContext.getUserValidationStatus() != -1){
					viewHold.tvNumber.setText(plateNumber);
				}else{
					plateNumber=plateNumber.substring(0, plateNumber.length()-2)+"**";
					viewHold.tvNumber.setText(plateNumber);
				}
//				viewHold.tvNumber.setText(info.getTruckPlateNumber());
				viewHold.tvNumber.setVisibility(View.VISIBLE);
			}
			
			if(StringUtil.isNull(info.getTruckerName())){
				viewHold.tvName.setText(info.getTruckerName());
				viewHold.tvName.setVisibility(View.GONE);
			}else{
				viewHold.tvName.setText(info.getTruckerName());
				viewHold.tvName.setVisibility(View.VISIBLE);
			}
			if (StringUtil.isNull(info.getTruckLength())) {
				viewHold.tvLength.setText("车长不限");
			} else {
				if(StringUtil.isEqual(info.getTruckLength(), "23")){
					viewHold.tvLength.setText(info.getTruckLength() + "米以上");
				}else{
					viewHold.tvLength.setText(info.getTruckLength() + "米");
				}
			}
			if (StringUtil.isNull(info.getTruckCapacity())) {
				viewHold.tvWeight.setText("载重若干");
			} else {
				viewHold.tvWeight.setText("载重" + info.getTruckCapacity() + "吨");
			}
			if(StringUtil.isNull(info.getTruckType())){
				viewHold.tvType.setVisibility(View.GONE);
			}else{
				viewHold.tvType.setText(info.getTruckType());
				viewHold.tvType.setVisibility(View.VISIBLE);
			}
			int status = info.getTruckStatus();
			//货车状态：0 待提交，1等待验证，2-验证失败，3-空闲中，4已接单
			if(status == 3){
				viewHold.tvStatus.setText("空闲中");
				viewHold.tvStatus.setBackgroundResource(R.drawable.btn_green_light_selector);
			}else{
				viewHold.tvStatus.setText("忙碌中");
				viewHold.tvStatus.setBackgroundResource(R.drawable.btn_orange_light_selector);
			}
			
			if(info.getTruckValidationStatus() == 0){
				viewHold.TruckValidation.setVisibility(View.GONE);
			}else if(info.getTruckValidationStatus() == 1){
				viewHold.TruckValidation.setImageResource(R.drawable.iv_truck_validation_successed);
				viewHold.TruckValidation.setVisibility(View.VISIBLE);
			}else{
				viewHold.TruckValidation.setImageResource(R.drawable.iv_truck_validation_failed);
				viewHold.TruckValidation.setVisibility(View.GONE);
			}
			
			viewHold.tvTime.setText(DateUtil.getInterval(info.getTruckUpdateTime()));
			viewHold.tvTime.setVisibility(View.GONE);
//			String description = info.getCargoDescription().trim().replace(",", "");
//			viewHold.tvDescription.setText(description);

			viewHold.layoutCollection.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(LContext.isLogin()){
						new CommonRequest(mContext, mHandler).addFavorite(info.getTruckId(), CommonConfig.OPERATE_OBJECT_TRUCK);
		        	}else{
		        		mContext.startActivity(new Intent(mContext, LoginActivity.class));
		        	}
				}
			});
			viewHold.layoutCall.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(LContext.isLogin()){
						new CommonRequest(mContext, new Handler()).saveOperateHistory(info.getTruckId(), CommonConfig.OPERATE_OBJECT_TRUCK, CommonConfig.OPERATE_CALL,"");
						if (LContext.getUserValidationStatus() != -1) {//认证完
							OnCallPhone(info);
						}else{//未认证通过
							ContactTrucker trucker = new ContactTrucker(mContext);
							trucker.setCallListener(new OnCallListener() {
								
								@Override
								public void onCall() {
									OnCallPhone(info);
								}
							});
						}
		        	}else{
		        		mContext.startActivity(new Intent(mContext, LoginActivity.class));
		        	}
				}
			});
			
			if (!StringUtil.isNull(info.getTruckCurrentCity())) {
				viewHold.tvCurrentCity.setText(info.getTruckCurrentCity());
			}
			
			StringBuilder sb = new StringBuilder();
			if (!StringUtil.isNull(info.getTruckForwardCity1())) {
				sb.append(info.getTruckForwardCity1()).append("    ");
			}
			if (!StringUtil.isNull(info.getTruckForwardCity2())) {
				sb.append(info.getTruckForwardCity2()).append("    ");
			}
			if (!StringUtil.isNull(info.getTruckForwardCity3())) {
				sb.append(info.getTruckForwardCity3()).append("    ");
			}
			if (!StringUtil.isNull(info.getTruckForwardCity4())) {
				sb.append(info.getTruckForwardCity4()).append("    ");
			}
			
			if (sb.length() > 0) {
				viewHold.tvForward.setText(sb.toString());
			}else{
				viewHold.tvForward.setText("未知");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return convertView;
	}

	private void OnCallPhone(TruckInfo info){
		if(!StringUtil.isNull(info.getTruckerPhone())){
			LContext.truckInfo = info;
			String mobileText = info.getTruckerPhone().replace("-", "");
			Intent intent = new Intent();// 创建一个意图对象，用来激发拨号的Activity
			intent.setAction("android.intent.action.CALL");
			intent.setData(Uri.parse("tel:" + mobileText));
			mContext.startActivity(intent);// 方法内部会自动添加类别,android.intent.category.DEFAULT
			LContext.isOrdered = true;
		}else{
			ToastHelper.toastShort(mContext, "该车主未提供联系电话");
		}
	}

	static class ViewHold{
		ImageView ivFull;//车辆照片
		TextView tvNumber;
		TextView tvName;
		TextView tvStatus;
		TextView tvCurrentCity;
		TextView tvForward;
		TextView tvType;
		TextView tvLength;
		TextView tvWeight;
		TextView tvTime;
		
		ImageView TruckValidation;
		
		LinearLayout layoutCollection;
		LinearLayout layoutCall;
	}

}
